import { defineConfig } from 'vite'
import { svelte } from '@sveltejs/vite-plugin-svelte'

// https://vitejs.dev/config/
export default defineConfig(({ command, mode }) => {
  // 打印全部环境变量，帮助诊断
  console.log('=============================================');
  console.log(`Vite命令: ${command}, 模式: ${mode}`);
  console.log(`NODE_ENV: ${process.env.NODE_ENV}`);
  console.log(`VITE_MODE: ${process.env.VITE_MODE}`);
  console.log(`VITE_API_BASE_URL: ${process.env.VITE_API_BASE_URL}`);
  console.log('=============================================');
  
  // 正确地确定是否为开发环境
  const isDev = mode !== 'production';
  
  // 优先使用环境变量中的API基础URL，否则根据环境模式选择
  const apiBaseUrl = process.env.VITE_API_BASE_URL || 
    (isDev ? 'http://localhost:5000' : 'http://localhost:4007');
  
  console.log(`使用API基础URL: ${apiBaseUrl}`);
  console.log(`当前环境: ${isDev ? '开发环境' : '生产环境'}`);
  
  return {
    plugins: [
      svelte({
        compilerOptions: {
          compatibility: {
            componentApi: 5
          }
        }
      })
    ],
    server: {
      strictPort: true,
      host: true,
      // 允许的域名列表
      allowedHosts: ['afa.sihuang.tech', 'localhost'],
      proxy: {
        '/api': {
          target: apiBaseUrl,
          changeOrigin: true,
          secure: false,
          // 不修改路径，使用/api前缀访问后端
          rewrite: (path) => {
            console.log(`Proxying ${path} to ${apiBaseUrl}`);
            return path;
          }
        },
        // 添加健康检查路径代理
        '/health': {
          target: apiBaseUrl,
          changeOrigin: true,
          secure: false
        }
      }
    },
    build: {
      outDir: 'dist',
      emptyOutDir: true,
      sourcemap: isDev,
      minify: !isDev,
      rollupOptions: {
        output: {
          manualChunks: {
            vendor: ['svelte', 'svelte/internal']
          }
        }
      }
    }
  }
}) 
